package com.atguigu.tingshu.user.context;

import com.atguigu.tingshu.user.strategy.UpdateUserPaidRecordStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class UpdateUserPaidRecordStrategyContext implements ApplicationContextAware {

    // 存放策略
    private static final Map<String, UpdateUserPaidRecordStrategy> PAYE_INFO_STRATGY_MAP = new HashMap<>();

    public static UpdateUserPaidRecordStrategy getStrategy(String itemType){
        return PAYE_INFO_STRATGY_MAP.get(itemType);
    }

    // 初始化 给策略赋值
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, UpdateUserPaidRecordStrategy> beansOfType = applicationContext.getBeansOfType(UpdateUserPaidRecordStrategy.class);
        beansOfType.values().forEach(updateUserPaidRecordStrategy->{
            String itemType = updateUserPaidRecordStrategy.getItemType();
            PAYE_INFO_STRATGY_MAP.put(itemType,updateUserPaidRecordStrategy);
        });
    }
}
